package cn.com.fuhuitong.main.order.ui.activity

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.Observer
import cn.com.fuhuitong.R
import cn.com.fuhuitong.app.AppConstance
import cn.com.fuhuitong.app.WX_APP_ID
import cn.com.fuhuitong.aroute.ARouteConstance
import cn.com.fuhuitong.base.ActivityCollector
import cn.com.fuhuitong.entity.MainBean
import cn.com.fuhuitong.entity.OrderAction
import cn.com.fuhuitong.entity.PayResult
import cn.com.fuhuitong.entity.PayType
import cn.com.fuhuitong.http.HttpResponseStatus
import cn.com.fuhuitong.main.base.ViewModeActivity
import cn.com.fuhuitong.main.goods.ui.activity.GoodsDetailsActivity
import cn.com.fuhuitong.main.order.entity.PayEntity
import cn.com.fuhuitong.main.order.entity.WXPayEntity
import cn.com.fuhuitong.main.order.vm.OrderViewModel
import cn.com.fuhuitong.utils.SpanUtils
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alipay.sdk.app.PayTask
import com.blankj.utilcode.util.LogUtils
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_order_pay_wait.*
import org.greenrobot.eventbus.EventBus
import java.lang.StringBuilder
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit

@Route(path = ARouteConstance.ACTIVITY_URL_ORDER_PAY_WAIT)
class OrderPayWaitActivity : ViewModeActivity<OrderViewModel>() {

    private var payType: PayType = PayType.WX_PAY

    private var payEntity: PayEntity? = null

    override fun viewModel(): OrderViewModel = createViewModel()

    override val layoutResId: Int
        get() = R.layout.activity_order_pay_wait

    override fun initView() {

        image_order_pay_back.setOnClickListener {
            this.onBackPressed()
        }

        payEntity = intent?.getSerializableExtra(AppConstance.BUNDLE_ORDER_PAY)
                as PayEntity

        payEntity?.let { fillData(it) }

        frame_order_pay_wx.setOnClickListener {
            check_order_pay_wx.isChecked = true
            check_order_pay_ali.isChecked = false
        }

        frame_order_pay_ali.setOnClickListener {
            check_order_pay_ali.isChecked = true
            check_order_pay_wx.isChecked = false
        }

        check_order_pay_wx.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) payType = PayType.WX_PAY
        }

        check_order_pay_ali.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) payType = PayType.ALI_PAY
        }

        text_order_pay_submit.setOnClickListener {
            if (payType == PayType.WX_PAY) {
                viewModel.wxPay(payEntity?.id.toString())
            } else if (payType == PayType.ALI_PAY) {
                viewModel.aliPay(payEntity?.id.toString())
            }
        }

    }

    override fun initViewMode() {
        viewModel.wxPayDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.let {
                wxPayView(entity = it)
            }
        })

        viewModel.aliPayDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.let {
                aliPayView(payString = it)
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 200) {
            this.finish()
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_ORDER_LIST)
            .withInt(AppConstance.BUNDLE_ORDER_STATUS, 1)
            .navigation()
    }

    override fun onEventMainThread(eventBus: MainBean<*, *>) {
        super.onEventMainThread(eventBus)
        if (eventBus.type !is PayResult) {
            return
        }
        if (eventBus.type == PayResult.SUCCESS) {
            ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_ORDER_PAY_COMPLETE)
                .withSerializable(
                    AppConstance.BUNDLE_PAY_MAIN,
                    MainBean(type = payType, data = payEntity?.pay_price)
                )
                .navigation(this, 200)
            EventBus.getDefault().post(
                MainBean(type = OrderAction.SUCCESS, data = null)
            )
        } else {
            toast(eventBus.type.desc)
        }
    }


    private fun getHours(second: Long): String { //计算秒有多少小时
        var h: Long = 0
        if (second > 3600) {
            h = second / 3600
        }
        return h.toString() + ""
    }

    private fun getMins(second: Long): String { //计算秒有多少分
        var d: Long = 0
        val temp = second % 3600
        if (second > 3600) {
            if (temp != 0L) {
                if (temp > 60) {
                    d = temp / 60
                }
            }
        } else {
            d = second / 60
        }
        return d.toString() + ""
    }

    private fun getSeconds(second: Long): String { //计算秒有多少秒
        var s: Long = 0
        val temp = second % 3600
        if (second > 3600) {
            if (temp != 0L) {
                if (temp > 60) {
                    if (temp % 60 != 0L) {
                        s = temp % 60
                    }
                } else {
                    s = temp
                }
            }
        } else {
            if (second % 60 != 0L) {
                s = second % 60
            }
        }
        return s.toString() + ""
    }

    /**
     * 初始数据
     * */
    private fun fillData(payEntity: PayEntity) {

        text_order_pay_price.text =
            SpanUtils.decimalFormat(payEntity.pay_price.toDouble())

        if (payEntity.order_remnant_time < 0) {
            text_order_pay_remnant_time.text = "支付超时"
            return
        }
        //从0开始、到60结束、延时0开始，单位时间
        val disposable: Disposable =
            Flowable.intervalRange(1, payEntity.order_remnant_time, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext {
                    val remnant: Long = payEntity.order_remnant_time - it
                    val hour: String = getHours(remnant)
                    val mins: String = getMins(remnant)
                    val second: String = getSeconds(remnant)
                    val sb: StringBuilder = StringBuilder("请在")
                        .append(if (hour.length == 1) "0$hour" else hour).append("小时")
                        .append(if (mins.length == 1) "0$mins" else mins).append("分")
                        .append(if (second.length == 1) "0$second" else second)
                        .append("秒内完成支付")
                    text_order_pay_remnant_time.text = sb.toString()
                }
                .doOnComplete {
                    text_order_pay_remnant_time.text = "支付超时"
                }
                .subscribe()
        viewModel.dispose().add(disposable)
    }

    /**
     * 拉起微信支付
     * */
    private fun wxPayView(entity: WXPayEntity) {
        val disposable: Disposable = Observable.just(WXAPIFactory.createWXAPI(this, null))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .filter {
                if (!it.isWXAppInstalled) {
                    toast("未安装微信")
                }
                it.isWXAppInstalled
            }
            .subscribe({ msgApi ->
                msgApi.registerApp(WX_APP_ID)
                msgApi.sendReq(PayReq().also {
                    it.appId = WX_APP_ID
                    it.partnerId = entity.partnerid
                    it.prepayId = entity.prepayid
                    it.packageValue = entity.`package`
                    it.nonceStr = entity.noncestr
                    it.sign = entity.sign
                    it.timeStamp = entity.timestamp
                    it.extData = "0"
                })
            }, {
                toast("微信支付-${it.message ?: "未知错误"}")
            })
        viewModel.dispose().add(disposable)
    }


    /**
     * 拉起支付宝支付
     * */
    private fun aliPayView(payString: String) {
        val disposable: Disposable = Observable.just(payString).map {
            PayTask(this).payV2(it, true)
        }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                val payResult: PayResult = when (it["resultStatus"]?.toInt()) {
                    9000 -> PayResult.SUCCESS
                    4000 -> PayResult.FAILURE
                    5000 -> PayResult.DUPLICATED
                    6001 -> PayResult.CANCEL
                    6002 -> PayResult.NETWORK
                    else -> PayResult.UNKNOWN
                }
                EventBus.getDefault().post(
                    MainBean(type = payResult, data = null)
                )
            }, {
                toast("支付宝支付-${it.message ?: "未知错误"}")
            })
        viewModel.dispose().add(disposable)
    }
}